from django.shortcuts import render, HttpResponse,redirect
from django.http import JsonResponse
from mng import models
import json
from django import views
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import simplejson
# Create your views here.

#定义返回数据格式
class loging(views.View):
#    def get(self, req, *args, **kwargs):
#        return render(req, "mng/login.html", {'message': ''})
#
    def post(self, req, *args, **kwargs):
        username = req.POST.get('username')
        pwd = req.POST.get('pwd')
        print(username, pwd)
        auth = models.Administrator.object.filter(name=username, pwd=pwd).count()
        if auth:
            req = redirect('mng/index.html')
            req.set_cookie("username", username, max_age=300)
            return req
        else:
            message = "账户或密码错误"
            return render(req, "mng/login.html", {'message': message})

def logout(req):
    req.delete_cookie('username')
    return redirect("mng/login.html")

def auth(func):
    def inner(req, *args, **kwargs):
        cookies = req.COOKIES.get("username", )
        print("cookies:", cookies)
        if cookies:
            return func(req, *args, **kwargs)
        else:
            return redirect("mng/login.html")
    return inner

@auth
def index(req):
    username = req.COOKIES.get("username")
    return render(req, "mng/index.html", {"username": username})

def register(req):
    if req.method == "POST":
        username = req.POST.get("name")
        print(username)
        pwd = req.POST.get("pwd")
        print(pwd)
        sex = req.POST.get("gender")
        rolse = req.POST.get("rolse")
        result = models.Administrator.object.filter(name=username).count()
        if not result:
            register = models.Administrator.object.create(**{"name": username, "pwd": pwd})
            register.save()
            return render(req, "mng/register_succeed.html", {"username": username})
    return render(req, "mng/register.html")

@csrf_exempt
def user_ajax(req):
    username = req.POST.get("username", None)
    result = models.Administrator.object.filter(name=username).count()
    if result:
        return HttpResponse("True")
    else:
        return HttpResponse("false")

#班级
@auth
def handle_class(req):
    response_dict = {"status": True, "error": None, "data": None}
    action = req.GET.get("action")
    if req.method == "GET":
        #序列化获取到数据为json格式
        result = models.Classes.object.all()
        cls_list = []
        for item in result:
            cls_list.append({
                "id": item.id,
                "caption": item.caption,
            })
        response_dict["data"] = cls_list
        return JsonResponse(response_dict)
        # return render(req, "mng/classes.html", {"username": current_user, "cls_list": cls_list})

    if req.method == "POST":
        revice_data = simplejson.loads(req.body)
        current_user = req.COOKIES.get("username")
        data = revice_data["data"]
        if action == "CREATE":
            obj = models.Classes.object.create(caption=data["caption"])
            response_dict["data"] = {"id": obj.id, "caption": obj.caption}

        elif action == "DELETE":
            try:
                models.Classes.object.filter(id=data["id"]).delete()
            except Exception as m:
                print(m)
                response_dict["status"] = False

        elif action == "EDIT":
            try:
                models.Classes.object.filter(id=data["id"]).update(caption=data["caption"])
            except Exception as m:
                print(m)
                response_dict["status"] = False
        else:
            response_dict["status"] = False
            response_dict["error"] = "标题不能为空"
        return HttpResponse(json.dumps(response_dict), content_type="application/json")
@auth
def handle_student(req):
    response_dict = {"status": True, "error": None, "data": None}
    if req.method == "GET":
        #获取学生信息
        result = models.Students.object.all()
        student_list = []
        for item in result:
            student_list.append({
            "id": item.id,
            "name": item.name,
            "sex": item.sex,
            "cls": item.cls.caption
            })
#        student_list = serializers.serialize("json", student_info)
        response_dict["data"] = student_list
        return JsonResponse(response_dict)

    if req.method == "POST":
        revice_data = simplejson.loads(req.body)
        current_user = req.COOKIES.get("username")
        data = revice_data["data"]
        action = req.GET.get("action")
        print("action:", action)
        if data["name"] and action == "CREATE":
            obj = models.Students.object.create(name=data["name"], sex=data["sex"], cls_id=data["cls_id"])
            response_dict["data"] = {"id": obj.id, "name": obj.name}

        elif action == "DELETE":
            try:
                models.Students.object.filter(id=data["id"]).delete()
            except Exception as m:
                print(m)
                response_dict["status"] = False

        elif data["name"] and action == "EDIT":
            try:
                models.Students.object.filter(id=data["id"]).update(name=data["name"], sex=data["sex"])
            except Exception as m:
                print(m)
                response_dict["status"] = False

        elif action == "SELECT":
            try:
                print(data["name"])
                # 一对多正向查询
                result = models.Students.object.filter(name=data["name"])
                result_list = []
                for item in result:
                    result_list.append(
                        {
                            'name': item.name,
                            'sex': item.sex,
                            'classes': item.cls.caption
                        }
                    )
                response_dict["data"] = result_list
            except Exception as m:
                print(m)
                response_dict["status"] = False
        else:
            response_dict["status"] = False
            response_dict["error"] = "标题不能为空"
        return JsonResponse(response_dict, safe=False)




@auth
def get_teacher(req):
    if req.method == "POST":
        #获取老师信息
        revice_data = simplejson.loads(req.body)
        pageSize = revice_data["pageSize"]
        pageIndex = revice_data["pageIndex"]
        if not pageSize:
            pageSize = 2
        result = models.TeacherClass.object.all()
        paginator = Paginator(result, pageSize)
        try:
            page_obj = paginator.page(pageIndex)
            print(pageIndex, page_obj.object_list)
        except PageNotAnInteger:
            #如果请求的页数不是整数，返回第一页。
            page_obj = paginator.page(1)
        except EmptyPage:
            #如果请求的页数不在合法页数范围内，返回结果的最后一页。
            page_obj = paginator.page(paginator.num_pages)

        teacher_list = {}
        for item in page_obj.object_list:
#            print(item.id, item.teacher.id, item.teacher.name, item.cls.id, item.cls.caption)
            #如果tearcher.id已经存在teacher_list中，则直接添加对应的课程
            print(item.teacher.id)
            if item.teacher.id in teacher_list:
                teacher_list[item.teacher.id]["cls_list"].append(
                    {
                        "cls_id": item.cls.id,
                        "capton": item.cls.caption
                    }
                )
            else:
                # 如果tearcher.id不存在teacher_list中，则先创建
                if item.cls.id:
                    temp = [{
                        "cls_id": item.cls.id,
                        "caption": item.cls.caption
                    }]
                teacher_list[item.teacher.id] = {
                    "id": item.teacher.id,
                    "name": item.teacher.name,
                    "cls_list": temp
                }
        response_dict = {"status": True, "errorCode": None, "message": None,
                         "content": {
                             "total": paginator.count,
                             "totalPage": paginator.num_pages,
                             "pageSize": pageSize,
                             "pageNum": pageIndex,
                             "data": teacher_list
                          }
                         }
        #print(response_dict)
        #return HttpResponse(teacher_list)
        return JsonResponse(response_dict)
@auth
def add_teacher(req):
    response_dict = {"status": True, "error": None, "data": None}
    if req.method == "POST":
        revice_data = simplejson.loads(req.body)
        current_user = req.COOKIES.get("username")
        data = revice_data["data"]
        action = req.GET.get("action")
        print("action:", action)
        #多对多 第三张表是自己创建的邦定方法
        obj = models.Teachers.object.create(name=data["name"])
        for i in data["cls_id"]:
            s = models.TeacherClass.object.create(teacher_id=obj.id, cls_id=i)
            s.save()
        response_dict["data"] = {"id": obj.id, "name": obj.name}
        return JsonResponse(response_dict)
@auth
def del_teacher(req):
    response_dict = {"status": True, "error": None, "data": None}
    if req.method == "POST":
        revice_data = simplejson.loads(req.body)
        current_user = req.COOKIES.get("username")
        data = revice_data["data"]
        action = req.GET.get("action")
    try:
        teacher = models.Teachers.object.filter(id=data["id"]).delete()
    except Exception as m:
        print(m)
        response_dict["status"] = False
    return JsonResponse(response_dict)


@auth
def edit1_teacher(req):
    """
    1.获取当前老师对应的所有班级
    2.获取当前所有班级
    :param req:
    :return:
    """
    response_dict = {"status": True, "error": None, "data": None}
    if req.method == "POST":
        revice_data = simplejson.loads(req.body)
        nid = revice_data['id']
        t_obj = models.TeacherClass.object.filter(teacher_id=nid).values("cls__id", "cls__caption")
        t_to_cls = []
        all_cls = []
        for item in t_obj:
            t_to_cls.append({
                "cls_id": item["cls__id"],
                "caption": item["cls__caption"]
            })
        cls_obj = models.Classes.object.all()
        for item in cls_obj:
            all_cls.append({
                "cls_id": item.id,
                "caption": item.caption
            })
        data = {
            "id": nid,
            "all_cls": all_cls,
            "t_to_cls": t_to_cls
        }
        response_dict['data'] = data
        return JsonResponse(response_dict)
@auth
def edit_teacher(req):
    response_dict = {"status": True, "error": None, "data": None}
    if req.method == "POST":
        revice_data = simplejson.loads(req.body)
        current_user = req.COOKIES.get("username")
        cls_id = revice_data["cls_id"]
        nid = revice_data["id"]
        name = revice_data["name"]
        try:
            #teacher_obj = models.Teachers.object.filter(id=nid).update(name=name)
            teacher_obj = models.Teachers.object.get(id=nid)
            teacher_obj.name = name
            teacher_obj.save()
            for i in cls_id:
                s = models.TeacherClass.object.create(teacher_id=nid, cls_id=i)
                s.save()
        except Exception as m:
            print(m)
            response_dict["status"] = False
        return JsonResponse(response_dict)

        # elif action == "ALLOT":
        #     print(data)
        #     models.TeacherClass.object.create(**data)
        #
        # elif action == "SELECT":
        #     try:
        #         teacher_obj = models.TeacherClass.object.filter(teacher__name=data["name"]).select_related("cls").all()
        #         result_list = []
        #         for item in teacher_obj:
        #             result_list.append(item.cls.caption)
        #         response_dict["data"] = {"teacher": data["name"], "classes": result_list}
        #     except Exception as m:
        #         print(m)
        #         response_dict["status"] = False
        # else:
        #     response_dict["status"] = False
        #     response_dict["error"] = "标题不能为空"
        # return JsonResponse(response_dict, safe=False)

def test(req):
    if req.method == "POST":
        #多对多正向查找
        ret1 = models.Teachers.object.filter(name='koko').all()
        for i in ret1:
           print(i.name)
           r = i.teacherclass_set.all()
           for item in r:
               print(item.id, item.cls.caption)

        #多对多反向查询
        # ret2 = models.TeacherClass.object.filter(teacher__name="lili").select_related("cls").all()
        # print(ret2)
        # for i in ret2:
        #     print(i.teacher.name, i.cls.caption)
        #
        # # 多对多(ManyToManyField()),表增加
        #
        # author1 = Author.objects.get(id=1)
        # author2 = Author.objects.filter(name='alvin')[0]
        # book = Book.objects.get(id=1)
        # book.authors.add(author1, author2)
        # # 等同于:
        # book.authors.add(*[author1, author2])
        # book.authors.remove(*[author1, author2])
        # # -------------------
        # book = models.Book.objects.filter(id__gt=1)
        # authors = models.Author.objects.filter(id=1)[0]
        # authors.book_set.add(*book)
        # authors.book_set.remove(*book)
        # # -------------------
        # book.authors.add(1)
        # book.authors.remove(1)
        # authors.book_set.add(1)
        # authors.book_set.remove(1)
        #
        # # 注意: 如果第三张表是通过models.ManyToManyField()自动创建的,那么绑定关系只有上面一种方式
        # #     如果第三张表是自己创建的:
        # class Book2Author(models.Model):
        #     author = models.ForeignKey("Author")
        #     Book = models.ForeignKey("Book")
        #     #     那么就还有一种方式:
        #     author_obj = models.Author.objects.filter(id=2)[0]
        #     book_obj = models.Book.objects.filter(id=3)[0]
        #
        #     s = models.Book2Author.objects.create(author_id=1, Book_id=2)
        #     s.save()
        #     s = models.Book2Author(author=author_obj, Book_id=1)
        #     s.save()

        return HttpResponse("OK")
